using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Ab2d;
using System.Windows.Controls;
using System.Windows.Markup;

namespace SvgXaml
{
	/// <summary>
	/// Author: Daniel Cazzulino.
	/// </summary>
	/// <remarks>
	/// Thanks Andrej Benedik (www.wpf-graphics.com) for the very cool ReaderSvg library!
	/// </remarks>
	class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			if (args.Length == 1 &&
				(args[0] == "/?" || args[0] == "-?"))
			{
				Console.WriteLine("Usage: Svg2Xaml [folder or file]+");
				Console.ReadLine();
				return;
			}

			Console.WriteLine("Thanks Andrej Benedik (www.wpf-graphics.com) for the very cool ReaderSvg library!");

			if (args.Length == 0)
			{
				ConvertDirectory(AppDomain.CurrentDomain.BaseDirectory);
			}
			else
			{
				foreach (string path in args)
				{
					if (Path.GetExtension(path) == ".svg")
					{
						ConvertFile(path);
					}
					else
					{
						ConvertDirectory(path);
					}
				}
			}

			Console.WriteLine("Done");
		}

		private static void ConvertFile(string file)
		{
			ReaderSvg reader = new ReaderSvg();
			try
			{
				using (Stream svg = File.OpenRead(file))
				{
					Viewbox box = reader.Read(svg);
					using (Stream xaml = File.Create(Path.ChangeExtension(file, ".xaml")))
					{
						XamlWriter.Save(box, xaml);
					}
				}
				File.AppendAllText("Success.txt", 
					Path.ChangeExtension(new FileInfo(file).FullName, ".xaml") + Environment.NewLine);
				Console.Write(".");
			}
			catch (Exception ex)
			{
				File.AppendAllText("Failed.txt",
					new FileInfo(file).FullName + ": " + ex.Message + Environment.NewLine);
				Console.Write("*");
			}
		}

		private static void ConvertDirectory(string directory)
		{
			foreach (string file in Directory.GetFiles(directory, "*.svg", SearchOption.AllDirectories))
			{
				ConvertFile(file);
			}
		}
	}
}
